# -*- coding:utf-8 -*-
__author__ = 'waxyfish'
__date__ = "2023-01-12"
__doc__ = "api接口列表"

import os
import traceback
from json import dumps
from json import loads
from datetime import datetime
from flask import g
from flask import request
from flask import send_file
from jsonpath import jsonpath
from loguru import logger

from app.API import APIbp
from app.utils.ResponseClient import result_msg
from app.utils.MySQLClient import MySQLClinet as mysql
from app.utils.RedisClient import RedisClinet as redis

@APIbp.route("/list")
def api_list():
    """
        获取所有接口列表
    """
    status = request.json.get('status') 
    sql = "select * from tb_api"
    if status in ['A','C']:
        sql += f" where status = '{status}'"
        
    data = mysql().query(sql)
    return result_msg(data=data)

@APIbp.route("/add",methods=['post'])
def api_add():
    """
        添加API接口
        {
            "apiName": "tgu登录成功",
            "apiData": {},
            "apiParams": {},
            "apiMethod": "post",
            "apiHeader": {"Content-Type": "application/json"},
            "apiUrl": "http://119.45.233.102:2244/testgoup/login",
            "apiJson": {"type": 1, "phone": "17674792729", "password": "a4f562b40a66e1c35470c9fbba9652e7"},
            "apiVariable": {"phone":"17674792729", "password":"a4f562b40a66e1c35470c9fbba9652e7"},
            "apiValidate": [{"eq": ["status_code", 200]}, {"eq": ["$.message", "登录成功！"]}],
            "apiExtract": [{"gtoken": "$..token"}]
        }
    """
    # 请求信息
    apiName = request.json.get("apiName")
    apiUrl = request.json.get("apiUrl")
    apiJson = request.json.get("apiJson")   # 选填
    apiData = request.json.get("apiData")   # 选填
    apiMethod = request.json.get("apiMethod")
    apiHeaders = request.json.get("apiHeaders")
    apiParams = request.json.get("apiParams")   # 选填
    apiRequest = {
        "url": apiUrl,
        "json": apiJson,
        "data": apiData,
        "method": apiMethod, 
        "headers": apiHeaders,
        "params": apiParams
    }
    apiVariable = request.json.get("apiVariable")
    apiValidate = request.json.get("apiValidate")
    apiExtract = request.json.get("apiExtract")

    # 字典格式转换成json格式
    apiRequest = dumps(apiRequest)
    apiVariable = dumps(apiVariable)
    apiValidate = dumps(apiValidate)
    apiExtract = dumps(apiExtract)

    sql = f"""INSERT INTO tb_api VALUES (null, 'A', '{apiName}', '{apiRequest}', '{apiVariable}', '{apiValidate}', '{apiExtract}', NULL, '', now(), now());"""
    data = mysql().commit(sql)
    res_code = 1 if data else 0 
    res_msg = "新增接口成功！" if data else "新增接口失败！"
    # logger.info(sql)
    return result_msg(res_code,res_msg)

@APIbp.route("/delete",methods=['post'])
def api_delete():
    """
        根据API的id进行逻辑删除
    """
    apiId = request.json.get("apiId")
    if not isinstance(apiId,int):
        return result_msg(0,"输入的ID格式错误！")

    sql = f"update tb_api set status = 'C' where id = {apiId}"
    data = mysql().commit(sql)
    res_code = 1 if data else 0 
    res_msg = "禁用成功！" if data else "禁用失败！"
    # logger.info(sql)
    return result_msg(res_code,res_msg)

@APIbp.route("/update",methods=['post'])
def api_update():
    """
        指定id对API进行修改
        {
            "apiId": 1,
            "apiName": "tgu登录成功",
            "apiData": {},
            "apiParams": {},
            "apiMethod": "post",
            "apiHeader": {"Content-Type": "application/json"},
            "apiUrl": "http://119.45.233.102:2244/testgoup/login",
            "apiJson": {"type": 1, "phone": "17674792729", "password": "a4f562b40a66e1c35470c9fbba9652e7"},
            "apiVariable": {"phone":"17674792729", "password":"a4f562b40a66e1c35470c9fbba9652e7"},
            "apiValidate": [{"eq": ["status_code", 200]}, {"eq": ["$.message", "登录成功！"]}],
            "apiExtract": [{"gtoken": "$..token"}]
        }
    """
    # 请求信息
    apiId = request.json.get("apiId")
    apiName = request.json.get("apiName")
    apiUrl = request.json.get("apiUrl")
    apiJson = request.json.get("apiJson")   
    apiData = request.json.get("apiData")   
    apiMethod = request.json.get("apiMethod")
    apiHeaders = request.json.get("apiHeaders")
    apiParams = request.json.get("apiParams")
    apiRequest = {
        "url": apiUrl,
        "json": apiJson,
        "data": apiData,
        "method": apiMethod, 
        "headers": apiHeaders,
        "params": apiParams
    }
    apiVariable = request.json.get("apiVariable")
    apiValidate = request.json.get("apiValidate")
    apiExtract = request.json.get("apiExtract")

    # 字典格式转换成json格式
    apiRequest = dumps(apiRequest)
    apiVariable = dumps(apiVariable)
    apiValidate = dumps(apiValidate)
    apiExtract = dumps(apiExtract)

    sql = f"UPDATE tb_api SET name='{apiName}', request='{apiRequest}', variable='{apiVariable}', validate='{apiValidate}', extract='{apiExtract}',updateTime=now() WHERE id={apiId};"
    data = mysql().commit(sql)
    res_code = 1 if data else 0 
    res_msg = "修改成功！" if data else "修改失败！"
    logger.info(sql)
    return result_msg(res_code,res_msg)